package cn.com.xcf.spring;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

/**
 * @author WongBin
 * @date 2017/11/8.
 */
@Configuration
public class PropertyLoaderConfig extends PropertyPlaceholderConfigurer {
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

        private static Logger logger = LoggerFactory.getLogger(PropertyLoaderConfig.class);
        private static String DEFAULT_CONF_FILE;
        private static String DEFAULT_CONF_FILE_LOCAL;
        private static boolean flag;
        private volatile List<StartUpExecutor> executers = new LinkedList();

        public PropertyLoaderConfig() {
            logger.info("\n*********************PropertyLoaderConfig constructor called******************************");
        }

        @Override
        protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException {
            Properties pro = loadFile();
            Iterator i$ = pro.keySet().iterator();

            while(i$.hasNext()) {
                Object key = i$.next();
                String keyStr = key.toString();
                String value = pro.getProperty(keyStr);
                if(null != keyStr && !keyStr.isEmpty()) {
                    AppContextConfig.put(keyStr, value);
                }
            }

            this.initExecutors();
            this.executeAll();
            logger.info("系统配置详情:");
            AppContextConfig.getConfigMap().entrySet().stream().filter((f) -> {
                return f.getKey() != null;
            }).sorted((s1, s2) -> {
                return ((String)s1.getKey()).compareTo((String)s2.getKey());
            }).forEach((val) -> {
                if(((String)val.getKey() + "").indexOf("password") == -1 && ((String)val.getKey() + "").indexOf("private") < 0) {
                    logger.info((String)val.getKey() + "=" + (String)val.getValue());
                } else {
                    logger.info((String)val.getKey() + "=******");
                }

                props.put(val.getKey(), val.getValue());
            });
            super.processProperties(beanFactoryToProcess, props);
        }

        private synchronized void initExecutors() {
            boolean isConnectConfigCenter = true;
            String str = AppContextConfig.get("isConnectConfigCenter");
            if(!StringUtils.isEmpty(str)) {
                try {
                    isConnectConfigCenter = Boolean.parseBoolean(str);
                } catch (Exception var4) {
                    isConnectConfigCenter = true;
                    logger.error("Failed to convet a string to a boolean, isConnectConfigCenter=" + str);
                }
            } else {
                isConnectConfigCenter = true;
            }

            if(isConnectConfigCenter) {
                logger.info("getting parameters from remote configuration center is enabled");
                //this.executers.add(new RemoteConfigInfoImpl());
            } else {
                logger.info("getting parameters from remote configuration center is disabled,isConnectConfigCenter=" + str);
            }

        }

        private synchronized void executeAll() {
            Properties properties = System.getProperties();
            properties.put("org.apache.cxf.stax.allowInsecureParser", "1");
            if(!flag) {
                Iterator var2 = this.executers.iterator();

                while(var2.hasNext()) {
                    StartUpExecutor executer = (StartUpExecutor)var2.next();
                    executer.execute();
                }

                flag = true;
            }

        }

        private static Properties loadWarFile() {
            Properties filePropIn = new Properties();
            InputStream input = null;

            try {
                input = Thread.currentThread().getContextClassLoader().getResourceAsStream(DEFAULT_CONF_FILE_LOCAL);
                if(input == null) {
                    ResourceBundle e = ResourceBundle.getBundle("env");
                    Set keys = e.keySet();
                    Iterator var4 = keys.iterator();

                    while(var4.hasNext()) {
                        String key = (String)var4.next();
                        filePropIn.put(key, e.getString(key));
                    }
                } else {
                    logger.info(input == null?"input=null,":"input not null,get-input-stream-from：" + DEFAULT_CONF_FILE_LOCAL);
                    filePropIn.load(input);
                }

                logger.info("项目内置配置文件env.properties加载成功!");
            } catch (Exception var14) {
                logger.warn("项目内置配置文件env.properties加载失败!使用默认外置配置文件！{}", var14.getMessage());
            } finally {
                if(input != null) {
                    try {
                        input.close();
                        input = null;
                    } catch (IOException var13) {
                        logger.error(var13.getMessage(), var13);
                    }
                }

            }

            return filePropIn;
        }

        private static Properties loadOutFile(String filePath) {
            Properties filePropOut = new Properties();
            FileInputStream input = null;

            try {
                input = new FileInputStream(filePath);
                filePropOut.load(input);
                logger.info("外置配置文件{}加载成功", filePath);
            } catch (Exception var12) {
                logger.error("外置配置文件" + filePath + "加载失败！{}", var12.getMessage());
            } finally {
                if(input != null) {
                    try {
                        input.close();
                        input = null;
                    } catch (IOException var11) {
                        logger.error(var11.getMessage(), var11);
                    }
                }

            }

            return filePropOut;
        }

        protected static Properties loadFile() {
            Properties properties = new Properties();
            properties.putAll(loadWarFile());
            if(properties.containsKey("app.name")) {
                String appName = properties.getProperty("app.name");
                DEFAULT_CONF_FILE = File.separator + "wls" + File.separator + "envconfig" + File.separator + appName + File.separator + "env.properties";
            }

            properties.putAll(loadOutFile(DEFAULT_CONF_FILE));
            return properties;
        }

        static {
            DEFAULT_CONF_FILE = File.separator + "wls" + File.separator + "envconfig" + File.separator + "env.properties";
            DEFAULT_CONF_FILE_LOCAL = "env.properties";
            flag = false;
        }
    }
